package com.three.crm.fragment;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.three.crm.MyApplication;
import com.three.crm.R;
import com.three.crm.base.BaseFragment;
import com.three.crm.bean.AreaBean;
import com.three.crm.bean.CompanyBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.location.AmapLocationUtil;
import com.three.crm.location.LocationReceiver;
import com.three.crm.page.company.CompanyDetailActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.SignUtil;
import com.three.crm.util.TString;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.Context.ALARM_SERVICE;

/**
 * 首页
 * created by lqd on 2024-01-06.
 */
public class HomeFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks,LocationSource{


    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(int index, String title) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt(AppConstant.INDEX, index);
        args.putString(AppConstant.KEY_TITLE, title);
        fragment.setArguments(args);
        return fragment;
    }

    public final static String[] PERMISSES = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE
    };
    private boolean hasPermiss = false;
    private MapView mMapView = null;
    private AMap aMap;
    private AmapLocationUtil locationUtil;
    private TextView tvLocation;
    private MyLocationStyle myLocationStyle = new MyLocationStyle();
    //位置更改监听
    private LocationSource.OnLocationChangedListener mListener;

    private static final int REQUEST_GET_AREA = 310;

    private TextView tvPartnerTotal,tvPartnerOk,tvPartnerBlack,tvSearch,tvProvince,tvCity;

    private List<AreaBean> provinceBeans,cityBeans,regionBeans;
    private int provinceId = 0,cityId = 0,areaId = 0,currentIndex = 0;
    //标点列表
    private List<Marker> markerList = new ArrayList<>();
    private List<CompanyBean> markCompany = null;

    @Override
    protected void initArguments(Bundle bundle) {}

    @Override
    protected int bindLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        initLocation();
        tvLocation = $(R.id.tv_location);
        mMapView = $(R.id.map);
        mMapView.onCreate(savedInstanceState);
        aMap = mMapView.getMap();

        tvPartnerTotal = $(R.id.tv_partner_total);
        tvPartnerOk = $(R.id.tv_partner_ok);
        tvPartnerBlack = $(R.id.tv_partner_black);

        tvSearch = $(R.id.tv_search);
        tvProvince = $(R.id.tv_province);
        tvCity = $(R.id.tv_city);

        initMap();

        onCheckPermission();
    }

    private void initMap() {
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(getActivity().getLayoutInflater().inflate(R.layout.layout_marker,null)));
        // 自定义精度范围的圆形边框颜色  都为0则透明
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度  0 无宽度
        myLocationStyle.strokeWidth(0);
        // 设置圆形的填充颜色  都为0则透明
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //设置最小缩放等级为16 ，缩放级别范围为[3, 20]
        aMap.setMinZoomLevel(12);
        aMap.getUiSettings().setAllGesturesEnabled(true);
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        aMap.addOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                CompanyBean companyBean = markCompany.get(Integer.parseInt(marker.getTitle()));
                if (companyBean != null) {
                    new XPopup.Builder(getActivity())
                            .isViewMode(true)
                            .autoDismiss(true)
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asCustom(new CompanyPopup(getContext(),companyBean))
                            .show();
                }
                return true;
            }
        });
    }

    private void initLocation() {
        locationUtil = new AmapLocationUtil(getActivity());
        locationUtil.initLocation();
        locationUtil.setOnCallBackListener(new AmapLocationUtil.onCallBackListener() {
            @Override
            public void onCallBack(double longitude, double latitude, AMapLocation location, boolean isSucdess, String address) {
                if (isSucdess){
                    if (mListener != null) {
                        mListener.onLocationChanged(location);
                    }
                }
            }
        });
    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(getActivity(),PERMISSES)){
            hasPermiss = true;
            startLocationService();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要使用定位,手机通讯录等权限，您是否同意?",
                    AppConstant.RC_PERMISSES, PERMISSES);
        }
    }

    private void startLocationService() {
//        PeriodicWorkRequest request =
//                new PeriodicWorkRequest.Builder(LocationWorker.class, 15
//                        , TimeUnit.MINUTES)
//                        .addTag("LocationWorker")
//                        .setConstraints(new Constraints.Builder()
//                                .setRequiredNetworkType(NetworkType.CONNECTED)
//                                .build())
//                        .build();
//        Log.i("TAG","执行任务初始化...");
//        WorkManager.getInstance(getActivity()).enqueue(request);
        if (locationUtil != null) {
            locationUtil.startLocation();
        }
//        Intent i = new Intent(context, LocationService.class);
//        context.startService(i);

        AlarmManager manager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
        int interval = 60 * 1000 * 15; //15分钟
        long triggerAtTime = System.currentTimeMillis();
        Intent locationIntent = new Intent(getActivity(), LocationReceiver.class);
        locationIntent.putExtra(AppConstant.INDEX,"location");
        PendingIntent pi = PendingIntent.getBroadcast(getActivity(),0,locationIntent,PendingIntent.FLAG_CANCEL_CURRENT);
        manager.setRepeating(AlarmManager.RTC_WAKEUP,triggerAtTime,interval,pi);
    }

    @Override
    public void initListener() {
        $(R.id.tv_search).setOnClickListener(this);
        $(R.id.ll_province).setOnClickListener(this);
        $(R.id.ll_city).setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            case R.id.tv_search:
                onSearch();
                break;
            case R.id.ll_province:
                showDialogFragment(0,provinceBeans);
                break;
            case R.id.ll_city:
                if (provinceId == 0) {
                    showToast("请先选择省/地区");
                } else {
                    showDialogFragment(1,cityBeans);
                }
                break;
        }
    }

    private void showDialogFragment(int index,List<AreaBean> mList) {
        if (TString.isEmpty(mList)) {
            showToast("暂无数据");
        } else {
            String title = "请选择省/地区";
            if (index == 0) {
                title = "请选择省/地区";
            } else if (index == 1) {
                title = "请选择市";
            } else if (index == 2){
                title = "请选择区/县";
            }
            String items[] = new String[mList.size()];
            for (int i = 0; i < mList.size(); i++) {
                AreaBean bean = mList.get(i);
                items[i] = bean.getName();
            }
            new XPopup.Builder(getActivity())
                    // .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .maxHeight(MyApplication.getPopupHeight())
                    .asBottomList(title, items,
                            null,
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    if (index == 0) {
                                        tvProvince.setText(text);
                                        provinceId = provinceBeans.get(position).getId();
                                        currentIndex = 1;
                                        tvCity.setText("市");
                                        cityId = 0;

                                        areaId = 0;
                                        cityBeans.clear();
                                        regionBeans.clear();
                                        queryAreaByCode(provinceId);
                                    } else if (index == 1) {
                                        tvCity.setText(text);
                                        cityId = cityBeans.get(position).getId();
                                        currentIndex = 2;

                                        areaId = 0;
                                        regionBeans.clear();
                                        onSearch();
                                       // queryAreaByCode(cityId);
                                    } else if (index == 2){

                                        areaId = regionBeans.get(position).getId();
                                    }
                                }
                            })
                    .show();
        }
    }

    private void onSearch() {
        if (provinceId == 0) {
            showToast("请先选择省/地区");
            return;
        }
        if (cityId == 0) {
            showToast("请选择市/县");
            return;
        }
        loadStatistics();
        loadCompany();
    }

    private void loadCompany() {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("pageNo",0);
            jsonObject.put("pageSize",100);
            jsonObject.put("keyword","");
            jsonObject.put("province_id",provinceId);
            jsonObject.put("city_id",cityId);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryCompanyList(getActivity(), AppConstant.QUERY_LIST, jsonObject, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void loadStatistics() {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("keyword","");
            jsonObject.put("province_id",provinceId);
            jsonObject.put("city_id",cityId);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryStatistics(getActivity(), AppConstant.QUERY_DETAIL, jsonObject, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData(Context context) {
        provinceBeans = new ArrayList<>();
        cityBeans = new ArrayList<>();
        regionBeans = new ArrayList<>();
        currentIndex = 0;
        queryAreaByCode(0);
    }

    private void queryAreaByCode(int code) {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("parent_id",code);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryArea(getActivity(), REQUEST_GET_AREA, jsonObject, callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CommonResultCallBack callBack = new CommonResultCallBack(getActivity()) {
        @Override
        public void onResult(String result, int requireCode) {
            hideLoading();
            Log.i("TAG","result="+result);
            if (requireCode == REQUEST_GET_AREA) {
                if (currentIndex == 0) {
                    provinceBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                } else if (currentIndex == 1) {
                    cityBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                } else if (currentIndex == 2) {
                    regionBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                }
            } else if (requireCode == AppConstant.QUERY_DETAIL) {
                if (!TString.isEmpty(result)) {
                    try {
                        JSONObject object = new JSONObject(result);
                        if (object != null) {
                            tvPartnerTotal.setText("" + object.getInt("companyNum"));
                            tvPartnerOk.setText("" + object.getInt("dealCompanyNum"));
                            tvPartnerBlack.setText("" + object.getInt("blackCompanyNum"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else if (requireCode == AppConstant.QUERY_LIST) {
                if (!TString.isEmpty(result)) {
                    List<CompanyBean> tempList = GsonUtils.parseJsonArrayWithGson(result,CompanyBean.class);
                    handleMarkCompany(tempList);//设置页面数据
                }
            } else if (requireCode == AppConstant.FORM_SUBMIT) {

            }
        }

        @Override
        public void onConnectTimeOut(Call call, Exception e, int requireCode) {
            showToast(e.getMessage());
            hideLoading();
        }

        @Override
        public void onFail(String msg, int requireCode) {
            showToast(msg);
            hideLoading();
        }
    };

    //自定义高德标点
    protected View getMarkerView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.layout_marker_company, null);
        return view;
    }

    private void handleMarkCompany(List<CompanyBean> mList) {
        if (markCompany != null) {
            markCompany.clear();
        }
        markerList.clear();
        aMap.clear();
        if (mList != null && mList.size() > 0) {
            markCompany = mList;
            for (int i = 0; i < mList.size(); i++) {
                CompanyBean bean = mList.get(i);
                double latitude = Double.parseDouble(bean.getLatitude());
                double longitude = Double.parseDouble(bean.getLongitude());
                String name = bean.getTitle();
                LatLng latLng = new LatLng(latitude,longitude);

                MarkerOptions markerOption = new MarkerOptions();
                markerOption.position(latLng);
                markerOption.draggable(true);
                //Double.parseDouble(lat);
                markerOption.title(String.valueOf(i));

                markerOption.icon(BitmapDescriptorFactory.fromView(getMarkerView()));

                Marker marker = aMap.addMarker(markerOption);
                //添加标点
                //Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).snippet("DefaultMarker"));
                markerList.add(marker);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("TAG","onresume");
        if (mMapView != null) {
            mMapView.onResume();
        }
        //startLocation();
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i("TAG","onPause");
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideLoading();
        if (locationUtil != null) {
            locationUtil.destroyLocation();
        }
        // mlocationClient.onDestroy();
        Log.i("TAG","onDestroyView");
//        if (mMapView != null) {
//            mMapView.onDestroy();
//        }
//        if (mlocationClient != null) {
//            mlocationClient.onDestroy();
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("TAG","onDestroy");
        hideLoading();
        if (locationUtil != null) {
            locationUtil.destroyLocation();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("TAG","onSaveInstanceState");
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
        startLocationService();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {
        showToast("好伤心，您将无法使用定位等相关功能");
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
        hideLoading();
    }

    private class CompanyPopup extends BottomPopupView {

        private CompanyBean companyBean;
        private TextView tvCompanyName,tvCompanyAddress,tvCompanyPhone;

        public void setCompanyBean(CompanyBean mcompanyBean) {
            this.companyBean = mcompanyBean;
        }

        public CompanyPopup(@NonNull Context context) {
            super(context);
        }

        public CompanyPopup(@NonNull Context context, CompanyBean companyBean) {
            super(context);
            this.companyBean = companyBean;
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.xpopup_company;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            tvCompanyName = findViewById(R.id.tv_company_name);
            tvCompanyAddress = findViewById(R.id.tv_company_address);
            tvCompanyPhone = findViewById(R.id.tv_company_phone);
            if (companyBean != null) {
                tvCompanyName.setText(companyBean.getTitle());
                tvCompanyAddress.setText(companyBean.getAddress());
                tvCompanyPhone.setText(companyBean.getPhone());
            }
            findViewById(R.id.btn_detail).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (companyBean != null) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(AppConstant.EXTRAS_DATA,companyBean.getId());
                        startActivity(CompanyDetailActivity.class,bundle);
                    }
                }
            });
        }
    }
}